use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
use nom::AsBytes;

use crate::http_request::HttpRequest;
use crate::http_response::{HttpResponse, ResponseStatusLine};

mod http_response;
mod http_request;
mod http_headers;
mod handlers;
mod router;
mod constants;

fn main() {
    // You can use print statements as follows for debugging, they'll be visible when running tests.
    println!("Logs from your program will appear here!");

    let listener = TcpListener::bind("127.0.0.1:4221").unwrap();
    for stream in listener.incoming() {
        match stream {
            Ok(mut _stream) => {
                println!("accepted new connection");

                thread::spawn(move || {
                    //读取请求内容
                    let mut read_buffer = [0; 1024];
                    let _ = _stream.read(&mut read_buffer);
                    //需要删除 null-terminated C-style 字符串
                    let raw_request: String = String::from_utf8_lossy(&read_buffer[..]).chars().filter(|&c| c != '\x00').collect();
                    let request_data: &str = raw_request.trim();
                    println!("The raw request data is: {}", request_data);

                    let http_request: HttpRequest = From::<&str>::from(request_data);

                    let route_result = router::route(http_request);
                    match route_result {
                        Err(error) => {
                            _stream.write_all(Into::<Vec<u8>>::into(HttpResponse::new(ResponseStatusLine::error(500, format!("{}", error).as_str()))).as_bytes()).expect("Error encountered during writing response content");
                        },
                        Ok(http_response) => {
                            _stream.write_all(Into::<Vec<u8>>::into(http_response).as_bytes()).expect("Error encountered during writing response content");
                        }
                    }
                });
            }
            Err(e) => {
                println!("error: {}", e);
            }
        }
    }
}
